package com.mashibing.service.impl;

import com.mashibing.internalcommon.constant.CommonStatusEnum;
import com.mashibing.internalcommon.constant.DriverCarConstants;
import com.mashibing.internalcommon.constant.IdentityConstants;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.request.DriverUserWorkStatus;
import com.mashibing.internalcommon.response.DriverUserExistsResponse;
import com.mashibing.internalcommon.response.NumberCodeResponse;
import com.mashibing.internalcommon.util.RedisPrefixUtils;
import com.mashibing.remote.DriverUserClient;
import com.mashibing.remote.VerificationCodeClient;
import com.mashibing.service.DriverUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class DriverUserServiceImpl implements DriverUserService {

    @Autowired
    private DriverUserClient driverUserClient;

    @Autowired
    private VerificationCodeClient verificationCodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult verificationDriverUser(String phoneNumber) {
        log.info("司机电话号码为：" + phoneNumber);

        // 调用feign远程服务，验证电话的有效性
        ResponseResult<DriverUserExistsResponse> result = driverUserClient.verificationDriverUser(phoneNumber);
        int ifExist = result.getData().getIfExist();
        if (ifExist == DriverCarConstants.DRIVER_NOT_EXISTS) {
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXITST.getCode(),CommonStatusEnum.DRIVER_NOT_EXITST.getMessage());
        }

        // 生成验证码
        ResponseResult<NumberCodeResponse> responseResult = verificationCodeClient.numberCode(6);
        int code = responseResult.getData().getNumberCode();
        log.info("对应手机验证码为：" + code);

        // 发送验证码给司机

        // 放入redis
        String key = RedisPrefixUtils.generatorKeyByPhone(phoneNumber, IdentityConstants.DRIVER_IDENTITY);
        stringRedisTemplate.opsForValue().set(key,code + "",2, TimeUnit.MINUTES);

        return ResponseResult.success("验证码已发送");
    }

    @Override
    public ResponseResult updateStatus(DriverUserWorkStatus driverUserWorkStatus) {
        return driverUserClient.updateStatus(driverUserWorkStatus);
    }

    @Override
    public ResponseResult getDriverCarBindingRelationship(String driverPhone) {
        return driverUserClient.getDriverCarRelationShip(driverPhone);
    }


}
